<template>
	<view class="submit-form" :style="{ direction: $store.state.dir }">
		<view class="page-title h2">
			{{ $t('submit.title') }}
		</view>
		<icon-label :text="$t('property.title')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="title" maxlength="128" />
		<icon-label :text="$t('select.region')" icon="icon-location"></icon-label>
		<view class="form-input" @click.stop="handleShow">
			<p class="line1" style="float: left;max-width: 90%;">{{area_name||'Please choose'}}</p>
			<u-icon name="arrow-right" style="float: right;margin-top:10px;"></u-icon>
		</view>
		<!-- <uni-data-select :clear="false" v-model="city" :localdata="cityItems" placeholder="Select"></uni-data-select> -->
		<icon-label :text="$t('property.mapLocation')" icon="icon-location"></icon-label>
		<view class="form-input" @click.stop="goWebView">
			<p class="line1" style="float: left;max-width: 90%;">{{mapname}}</p>
			<u-icon name="arrow-right" style="float: right;margin-top:10px;"></u-icon>
		</view>
		<!-- 	<icon-label :text="$t('property.mapLocation')" icon="icon-location"></icon-label>
		<input class="form-input" v-model="mapname" maxlength="50" /> -->
		<icon-label :text="$t('property.address')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="address" />

		<icon-label :text="$t('property.label')" icon="icon-description"></icon-label>
		<input class="form-input" v-model="labels" placeholder="airport, mesum" />
		<!-- <icon-label text="short stay rentals" icon="icon-pay"></icon-label>
		<view class="flex-layout-row" style="margin-top: 28rpx;">
			<input class="form-input" v-model="familyPrice" style="width: 80%;"
				:placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">EGP</span>
		</view> -->
		<!-- <u-checkbox-group v-model="typeCheckbox" placement="column" @change="checkboxChange">
			<view class="" v-for="(item, index) in typeItems" :key="index" style="margin-bottom: 30rpx;">
				<u-checkbox :label="item.text" :name="item.value" style="margin-bottom: 10rpx;">
				</u-checkbox>
				<view class="flex-layout-row" style="margin-left: 40rpx;margin-top: 28rpx;">
					<input class="form-input" v-if="index==0" v-model="rentPrice" style="width: 30%;"
						:placeholder="$t('property.price')" />
					<input class="form-input" v-if="index==1" v-model="secondPrice" style="width: 30%;"
						:placeholder="$t('property.price')" />
					<input class="form-input" v-if="index==2" v-model="newPrice" style="width: 30%;"
						:placeholder="$t('property.price')" />
					<input class="form-input" v-if="index==3" v-model="familyPrice" style="width: 30%;"
						:placeholder="$t('property.price')" />
					<uni-data-select :clear="false" class="gap-row" style="width: 40%;" v-model="unit"
						:localdata="unitItems" placeholder="Select"></uni-data-select>
					<text
						style="width: 30%;display: inline-block;height:70rpx;line-height: 70rpx;">{{item.value==1?'Monthly':item.value==2?'Daily':''}}</text>

				</view>
			</view>


		</u-checkbox-group> -->
		<!-- <icon-label :text="$t('property.discount')" icon="icon-pay"></icon-label>
		<view class="flex-layout-row" style="margin-top: 28rpx;">
			<input class="form-input" v-model="discount" style="width: 80%;"
				:placeholder="$t('property.discount')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">EGP</span>
		</view> -->
		<view class="info_radio">
			<ul>
				<li :class="furnished==index?'active row':'row'" v-for="(item, index) in radioList" :key="index"
					@click.stop="handleRadio(index)">
					<image v-if="furnished == index" src="/static/choose-active.png" mode=""> </image>
					<image v-else src="/static/choose-gray.png" mode=""></image>
					<p>{{ item.name }}</p>
				</li>
			</ul>
		</view>
		<view v-if="furnished==0">
			<icon-label :text="$t('property.price')" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="rentPrice" style="width: 80%;" :placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.month') }}</span>
			</view>
		</view>
		<view v-if="furnished==1">
			<icon-label :text="$t('title.day')" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="familyPrice" style="width: 80%;"
					:placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label :text="$t('title.week')+'(7-15days)'" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;justify-content: space-between;">
				<view class="row">
					<input class="form-input" type="number" maxlength="3" v-model="weekDiscount"
						style="width: 60%;margin-right: 10rpx;" :placeholder="$t('property.discount')" />%<span
						style="margin-left: 24rpx;" v-if="weekPrice>0">{{weekPrice}}</span>
				</view>

				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label :text="$t('title.month')+'(16-30days)'" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;justify-content: space-between;">
				<view class="row">
					<input class="form-input" type="number" maxlength="3" v-model="monthDiscount"
						style="width: 60%;margin-right: 10rpx;" :placeholder="$t('property.discount')" />%<span
						style="margin-left: 24rpx;" v-if="monthPrice>0">{{monthPrice}}</span>
				</view>
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.day') }}</span>
			</view>
			<icon-label text="Longterm" icon="icon-pay"></icon-label>
			<view class="flex-layout-row" style="margin-top: 28rpx;">
				<input class="form-input" v-model="rentPrice" style="width: 80%;" :placeholder="$t('property.price')" />
				<span style="padding-left: 30rpx;line-height:80rpx;">{{ $t('text.egp.month') }}</span>
			</view>
		</view>

		<icon-label :text="$t('property.cleanfee')" icon="icon-pay"></icon-label>
		<view class="flex-layout-row" style="margin-top: 28rpx;">
			<input class="form-input" v-model="cleanfee" style="width: 80%;" :placeholder="$t('property.cleanfee')" />
			<span style="padding-left: 30rpx;line-height:80rpx;">EGP</span>
			<!-- <uni-data-select :clear="false" class="gap-row" style="width: 40%;" v-model="unit"
				:localdata="unitItems" placeholder="Select"></uni-data-select> -->
		</view>
		<icon-label :text="$t('property.houseType')" icon="icon-property-type"></icon-label>

		<uni-data-select :clear="false" v-model="houseType" :localdata="houseItems"
			placeholder="Select"></uni-data-select>
		<icon-label :text="$t('property.bedrooms')" icon="icon-bedroom"></icon-label>
		<input type="number" class="form-input" v-model="bedrooms" />
		<icon-label :text="$t('property.bathrooms')" icon="icon-bathroom"></icon-label>
		<input type="number" class="form-input" v-model="bathrooms" />
		<icon-label :text="$t('property.area')" icon="icon-area"></icon-label>
		<input type="decimal" class="form-input" v-model="area" />
		<!-- <icon-label :text="$t('property.price')" icon="icon-pricetag"></icon-label>
		<view class="flex-layout-row">
			<input class="form-input" v-model="price" />
			<uni-data-select :clear="false" class="gap-row" v-model="unit" :localdata="unitItems"
				placeholder="Select"></uni-data-select>
			<uni-data-select :clear="false" v-model="period" :localdata="periodItems"
				placeholder="Select"></uni-data-select>
		</view> -->
		<view class="row">
			<icon-label :text="$t('property.images')" icon="icon-bedroom"></icon-label><text class="copy"
				@click.stop="handleCopy">{{$t('property.url.title')}}</text>
		</view>

		<u-upload :fileList="images" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="30"></u-upload>
		<icon-label :text="$t('property.description')" icon="icon-description"></icon-label>
		<textarea v-model="description" confirm-hold :maxlength="1000"></textarea>
		<view class="free">
			<p>Free refund days for early cancellation of reservation</p>
			<p class="lg" style="color: #000000;" @click="isDays=true">{{canceldays+$t('title.days')}}</p>
			<text>If the free period is exceeded, the user will be charged extra fee, the house owner will receive 10% of the order amount</text>
		</view>
		<u-button class="gap-col-top2" type="primary" shape="circle" @click="handleSubmit">
			{{ $t('submit.submitButton') }}
		</u-button>
		<u-picker :show="isPopup" ref="uPicker" :cancelText="$t('text.cancel')" confirmText="confirm" :columns="columns"
			@cancel="handleCancel" @confirm="handleConfirm" @change="changeHandler"></u-picker>
	<u-picker :show="isDays" :columns="daysList" @cancel="handleCanceDays" :cancelText="$t('text.cancel')" :confirmText="$t('text.confirm')"			@confirm="onConfirmDays"></u-picker>
	</view>
</template>

<script>
	import {
		showFailure,
		showMessage,
		showSuccess
	} from '../../lib/helper';
	import {
		getAllLocationTree,
		getCityList,
		policy,
		submitHouse,
		getArea,
		getAllArea
	} from '../../lib/service';
	import {
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {
				mapname: this.$t('property.title.select.loaction'),
				longitude: "", //经度
				latitude: "", //纬度
				address: '',
				title: '',
				type: '1',
				canceldays:"0",
				typeCheckbox: ['4'],
				isDays:false,
				furnished: 0,
				radioList: [{
						name: this.$t('unfurnished'),
					},
					{
						name: this.$t('furnished'),
					}
				],
				floor: '',
				bedrooms: 5,
				bathrooms: 3,
				houseType: '2',
				area: 140,
				price: 1000,
				weekDiscount: "",
				monthDiscount: "",
				rentPrice: "",
				familyPrice: "",
				unit: '1',
				period: '2',
				description: '',
				images: [],
				isPopup: false,
				country: [],
				city: [],
				region: [],
				columns: [],
				countryIndex: 0,
				cityIndex: 0,
				regionIndex: 0,
				countryId: "", //国家id
				cityId: "", //城市id
				regionId: "", //地区id
				area_name: "",
				labels: "",
				discount: "",
				cleanfee: "",
				mapUrl: "",
				daysList: [					['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']				],
			};
		},
		onLoad(options) {
			this.handleAreaAll()
			//接收webview传值,能拿到经纬度 详细地址等信息
			// #ifdef APP-PLUS
			uni.$on("googleMsg", this.handleMessage1);
			// #endif
			// #ifdef H5
			window.addEventListener('message', this.handleMessage);
			// #endif
			// if (uni.getSystemInfoSync().platform === 'android' || uni.getSystemInfoSync().platform === 'ios') {
			// 	uni.$on("googleMsg", this.handleMessage1);
			// } else {
			// 	window.addEventListener('message', this.handleMessage);
			// }
		},
		onShow() {
			let _this = this;
			uni.$on("isRefresh", function(data) {
				let images = data.images;
				_this.images = _this.images.concat(images)
			});
		},
		computed: {
			...mapGetters({
				cityItems: 'cityList',
				typeItems: 'saleType',
				houseItems: 'houseType',
				periodItems: 'pricePeriod',
				unitItems: 'priceUnit'
			}),
			weekPrice() {
				return this.familyPrice * (1 - this.weekDiscount / 100)
			},
			monthPrice() {
				return this.familyPrice * (1 - this.monthDiscount / 100)
			},
		},
		methods: {
			handleMessage(event) {
				if (!event.data.data) return;
				// 处理接收到的数据
				const {
					action,
					addresstxt,
					longitude,
					latitude
				} = event.data.data.arg;
				console.log('Received data from WebView-H5:', event.data);
				if(action === "chooseaddress"){
					this.mapname = addresstxt||this.$t('property.title.select.loaction');
					this.longitude = longitude; //经度
					this.latitude = latitude; //纬度
				}
			},
			handleMessage1(event) {
				if (!event.action) return;
				// 处理接收到的数据
				const {
					action,
					addresstxt,
					longitude,
					latitude
				} = event;
				console.log('Received data from WebView-APP:', event);
				if(action === "chooseaddress"){
					this.mapname = addresstxt||this.$t('property.title.select.loaction');
					this.longitude = longitude; //经度
					this.latitude = latitude; //纬度
				}
			},
			handleCanceDays(e){
				this.isDays = false;
				 console.log(e)
			},
			onConfirmDays(e){
				this.isDays = false;
				this.canceldays = e.value[0];
			},
			deletePic(event) {
				this.images.splice(event.index, 1);
			},
			handleRadio(index) {
				this.furnished = index;
			},
			reset() {
				this.cityId = '';
				this.countryId = '';
				this.regionId = "";
				this.area_name = '';
				this.address = '';
				this.title = '';
				this.type = 1;
				this.floor = '';
				this.bedrooms = 5;
				this.bathrooms = 3;
				this.houseType = '2';
				this.area = 140;
				this.labels = '';
				this.cleanfee = '';
				this.rentPrice = "";
				this.familyPrice = '';
				this.weekDiscount = "";
				this.monthDiscount = "";
				this.unit = '1';
				this.period = '2';
				this.description = '';
				this.images = [];
				this.longitude = ""; //经度
				this.latitude = ""; //纬度
				this.mapname = "";
			},
			// 所有城市数据
			handleAreaAll() {
				let _this = this;
				getAllArea().then(res => {
					if (res.statusCode == 0) {
						let data = res.data.country;
						if (data.length > 0) {
							_this.country = data;
							_this.countryId = _this.country[_this.countryIndex].id;
							_this.handleArea(_this.country[_this.countryIndex].city)
						}
					}
				})
			},
			handleArea(city) {
				let _this = this;
				this.city = city || [];
				if (_this.city.length > 0) {
					_this.cityId = this.cityId ? this.cityId : _this.city[_this.cityIndex].id;
					_this.handleCity(_this.city[_this.cityIndex].region)
				}
			},
			handleCity(region) {
				let _this = this;
				_this.region = region || [];
				if (_this.region.length > 0) {
					_this.regionId = _this.regionId ? _this.regionId : _this.region[_this.regionIndex].id;
				}
				_this.buildTree(_this.country, _this.city, _this.region);
			},
			buildTree(country, city, region) {
				let _this = this;
				let columns = [
					[],
					[],
					[]
				];
				let array = [];
				let array1 = [];
				let array2 = [];
				country.forEach(item => {
					array.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				city.forEach(item => {
					array1.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				region.forEach(item => {
					array2.push(_this.$i18n.locale == 'en' ? item.name : item.name2)
				})
				columns[0] = array;
				columns[1] = array1;
				columns[2] = array2;
				this.columns = columns;
			},

			handleSubmit() {
				let _this = this;
				if (this.title.length <= 0) {
					showMessage(this.$t('message.title.wrong'));
					return;
				}
				if (!_this.countryId && !_this.cityId) {
					showMessage('Please select region');
					return;
				}
				if (_this.furnished == 1) {
					if (!_this.familyPrice&&!_this.rentPrice) {
						showMessage('Please enter the long-term or short-term rental price');
						return;
					}
					if (_this.weekDiscount < 0 && _this.weekDiscount > 100) {
						showMessage('Weekly discount input range 1-100');
						return;
					}
					if (_this.monthDiscount < 0 && _this.monthDiscount > 100) {
						showMessage('Monthly discount input range 1-100');
						return;
					}
					if(_this.familyPrice){
						_this.type = 4
					}
					if(_this.rentPrice){
						_this.type = 1
					}
					if(_this.familyPrice&&_this.rentPrice){
						_this.type = 14
					}
				}else{
					_this.type = 1;
					if (!_this.rentPrice) {
						showMessage(this.$t('message.title.rent'));
						return;
					}
					
				}
				if (this.images.length <= 0) {
					showMessage(this.$t('message.images.wrong'));
					return;
				}
				var images = this.images.map((item) => item.url);
				var data = {
					title: this.title,
					countryId: this.countryId,
					cityId: this.cityId,
					regionId: this.regionId,
					mapname: this.mapname,
					longitude: this.longitude,
					latitude: this.latitude,
					address: this.address,
					canceldays:this.canceldays,
					area: this.area,
					type: this.type,
					roomNum: this.bedrooms,
					toiletNum: this.bathrooms,
					propertyType: this.houseType,
					furnished: this.furnished,
					labels: this.labels,
					cleanfee: this.cleanfee,
					rentPrice: this.rentPrice,
					familyPrice: this.familyPrice,
					payPeriodType: this.period,
					payUnitType: this.unit,
					photoUrls: images.join(','),
					logo: images[0],
					remark: this.description
				};
				if (this.furnished == 1) {
					data['weekDiscount'] = this.weekDiscount;
					data['monthDiscount'] = this.monthDiscount;
				}
				uni.showLoading();
				submitHouse(data).then((res) => {
						uni.setStorageSync('location', null)
						showSuccess();
						uni.hideLoading();
						this.reset();
						uni.switchTab({
							url: '/pages/user/user'
						});
					})
					.catch((err) => {
						uni.hideLoading();
						showFailure();
					});
			},
			handleShow() {
				this.isPopup = true;

			},
			handleCancel(e) {
				console.log(e)
				this.isPopup = false;
			},
			handleConfirm(e) {
				this.area_name = e.value.join('-');
				this.isPopup = false;
			},
			changeHandler(e) {
				let _this = this;
				let indexs = e.indexs;
				let value = e.value;
				let countryIndex = indexs[0];
				let cityIndex = indexs[1];
				let regionIndex = indexs[2];
				if (e.columnIndex == 0 && countryIndex >= 0) {
					_this.countryIndex = countryIndex;
					this.countryId = _this.country[countryIndex].id;
					_this.handleAreaAll()
				} else if (e.columnIndex == 1 && cityIndex >= 0) {
					_this.countryIndex = countryIndex;
					_this.cityIndex = cityIndex;
					_this.countryId = _this.country[countryIndex].id;
					_this.cityId = _this.city[cityIndex].id;
					_this.handleAreaAll()
				} else if (e.columnIndex == 2 && regionIndex >= 0) {
					_this.regionIndex = regionIndex;
					_this.regionId = this.region[regionIndex].id;
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.images.length;
				lists.map((item) => {
					this.images.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i]);
					let item = this.images[fileListLen];
					this.images.splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(file) {
				let name = file.name ? file.name : file.url.split('/').pop();
				return new Promise((resolve, reject) => {
					policy('house', name).then((res) => {
						let a = uni.uploadFile({
							url: res.data.signedUrl, // 仅为示例，非真实的接口地址
							filePath: file.url,
							name: 'file',
							success: (res) => {
								try {
									var data = JSON.parse(res.data);
									resolve(data.data);
								} catch (e) {
									console.log(e);
								}
							}
						});
					});
				});
			},
			checkboxChange(e) {
				this.typeCheckbox = e;
				this.type = this.typeCheckbox.join('');
			},
			goWebView() {
				let language = uni.getStorageSync('language') || 'en';
				//该功能只能真机使用 仅限于 App  .nvue
				// #ifdef APP-PLUS
				uni.navigateTo({
					url: "./searchLocationApp?type=add&language=" + language
				})
				// #endif

				// #ifdef H5
				uni.navigateTo({
					url: "./searchLocation?type=add&language=" + language
				})
				// #endif
			},
			// 获取地图定位
			chooseLocation() {
				let _this = this;
				let language = uni.getStorageSync('language') || 'en';
				if (uni.getSystemInfoSync().platform === 'android' || uni.getSystemInfoSync().platform === 'ios') {
					console.log('运行Android上运行iOS上')
					uni.navigateTo({
						url: "./searchLocationApp?type=add&language=" + language
					})
				} else {
					console.log('运行H5上')
					uni.navigateTo({
						url: "./searchLocation?type=add&language=" + language
					})
				}
			},
			convertToWGS84(lat, lon) {
				return new Promise((resolve, reject) => {
					// 腾讯地图API转换接口
					const url =
						`https://apis.map.qq.com/ws/coord/v1/translate?from=0&to=5&locations=${lon},${lat}&key=6ORBZ-GH6C7-ENFXO-PQOGA-EZTYQ-NQBED`;

					uni.request({
						url: url,
						success: (res) => {
							if (res.statusCode == 200 && res.data.status == 0) {
								resolve({
									latitude: res.data.result[0].lat,
									longitude: res.data.result[0].lng
								});
							} else {
								reject('Error converting coordinates');
							}
						},
						fail: (error) => {
							reject(error);
						}
					});
				});
			},
			handleCopy() {
				uni.navigateTo({
					url: "./copyUrl"
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.free{
		background: #f8f8f8;
		border-radius: 12rpx;
		margin: 24rpx 0;
		color: #999999;
		font-size: 24rpx;
		padding: 20rpx 30rpx;
		p{
			margin-bottom: 24rpx;
		}
	}
	.info_radio {
		margin-top: 40rpx;

		ul {
			display: flex;
			align-items: center;

			.active {
				p {
					color: #2879FF;
				}
			}

			li {
				margin-right: 70rpx;

				image {
					width: 36rpx;
					height: 36rpx;
				}

				p {
					padding-left: 16rpx;
					color: #999999;
				}
			}
		}
	}

	.submit-form {
		padding: 10px 30px 20px 30px;

		.form-item-title {
			margin-top: 20px;
			display: flex;
			align-items: center;
		}

		.copy {
			font-size: 24rpx;
			margin-top: 16rpx;
			display: inline-block;
			margin-left: 10rpx;
			color: #1890ff;
		}

		.form-input {}

		textarea {
			height: 140px;
			border: 1px solid $app-border-color;
			border-radius: 4px;
			width: 100%;
			padding: 10px;
			box-sizing: border-box;
		}
	}
</style>